/*	$Id: msgtest.c 983 2009-09-01 02:45:42Z phrakt $	*/
/*
 * Copyright (c) 2008 Jean-Francois Brousseau <phrakt@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/types.h>
#include <sys/stat.h>

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

#include <canopy/log.h>

#include <http/http.h>
#include <http/msg.h>

#include "test.h"


struct msg_test {
	char               *msg_file;
	enum http_version   msg_version;
	int                 msg_hdr_count;
} tests[] = {
	{
		"test1.msg", HTTP_VERSION_10,
	},
	{
		"test-firefox-req1.msg", HTTP_VERSION_11,
	},
};


int
test_parse_msg(struct msg_test *test)
{
	int fd;
	void *buf;
	const char *val;
	http_msg_t *msg;
	struct stat st;

	test_log("Testing parsing of %s", test->msg_file);

	if (stat(test->msg_file, &st) == -1) {
		test_log("Failed to stat %s", test->msg_file);
		return (TEST_FAIL);
	}

	if ((buf = malloc(st.st_size)) == NULL) {
		test_log("Failed to allocate buffer");
		return (TEST_FAIL);
	}

	if ((fd = open(test->msg_file, O_RDONLY)) == -1) {
		test_log("Failed to open HTTP message source file %s",
		    test->msg_file);
		return (TEST_FAIL);
	}

	if (read(fd, buf, (size_t)st.st_size) != (ssize_t)st.st_size) {
		test_log("Failed to read %zu bytes from %s",
		    (size_t)st.st_size, test->msg_file);
		return (TEST_FAIL);
	}

	(void)close(fd);

	msg = http_msg_parse(buf, (size_t)st.st_size);
	if (msg == NULL) {
		test_log("Failed to parse message");
		return (TEST_FAIL);
	}

	free(buf);

	return (TEST_OK);
}


int
main(int argc, char **argv)
{
	int result;
	unsigned int i;

	http_init();
	test_init();

	for (i = 0; i < (sizeof(tests) / sizeof(tests[0])); i++) {
		test_start("test_parse_msg");
		result = test_parse_msg(&tests[i]);
		test_end(result);
	}

	test_cleanup();

	return (0);
}
